import { validatenull } from '@/utils/validate';
import { getToken } from '@/utils/auth';
import store from '@/store';

const errorNotifys = [];
const tipNotifys = [];

/*
 *打开错误提示框
 * */
export function openNotify(obj, title, message, htmlString, type) {
	console.log('openNotify');
	deleteAllNotify(obj);
	setTimeout(() => {
		if(Array.isArray(message)) {
			let messageTemp = '';
			for(let i in message) {
				messageTemp += message[i] + '</br>';
			}
			message = JSON.parse(JSON.stringify(messageTemp));
		}
		if(validatenull(type)) {
			errorNotifys.push(obj.$notify({
				title: validatenull(type) ? title : title.replace('错误', ''),
				dangerouslyUseHTMLString: htmlString || false,
				message: message,
				duration: 0,
				type: validatenull(type) ? 'error' : type,
				onClose: function(e) {
					for(const i in errorNotifys) {
						if(errorNotifys[i].id == e.id) {
							delete errorNotifys[i];
						}
					}
				}
			}));
		} else {
			tipNotifys.push(obj.$notify({
				title: validatenull(type) ? title : title.replace('错误', ''),
				dangerouslyUseHTMLString: htmlString || false,
				message: message,
				duration: 0,
				type: validatenull(type) ? 'error' : type,
				onClose: function(e) {
					for(const i in tipNotifys) {
						if(tipNotifys[i].id == e.id) {
							delete tipNotifys[i];
						}
					}
				}
			}));
		}
	}, 100);
}

/*
 *删除所有错误提示框
 * */
export function deleteAllNotify(obj) {
	//console.log('deleteAllNotify')
	for(const i in errorNotifys) {
		errorNotifys[i].close();
		delete errorNotifys[i];
	}
	setTimeout(() => {
		for(const i in tipNotifys) {
			tipNotifys[i].close();
			delete tipNotifys[i];
		}
	}, 5000);
}

/**
 *弹出询问框
 * obj this
 * data 数据
 * title 标题
 * content 内容
 * type 确定type success/error/info/warning
 * confirmText 确定文字
 * cancelText 取消文字
 * confirmFun 确定调用方法
 * cancelFun 取消调用方法
 */
export function openConfirm(obj, data, title, content, type, confirmText, cancelText, confirmFun, cancelFun) {
	obj.$confirm(content, (validatenull(title) ? '提示' : title), {
		confirmButtonText: validatenull(confirmText) ? '确定' : confirmText,
		cancelButtonText: validatenull(cancelText) ? '取消' : cancelText,
		type: validatenull(type) ? 'warning' : type
	}).then(() => {
		obj[confirmFun](data);
	}).catch(() => {
		if(!validatenull(cancelFun)) {
			obj[cancelFun](data);
		}
	});
}

/**
 *弹出消息
 * obj this
 * message 消息
 * showClose 显示关闭按钮
 * type 确定type success/error/info/warning
 * duration 自动关闭时间
 */
export function openMessage(obj, message, showClose, type, duration) {
	if(!validatenull(type) && typeof(type) == 'number') {
		if(type === 2000) {
			type = 'success';
		} else if(type === 2050) {
			type = 'error';
		}
	}
	setTimeout(() => {
		obj.$message({
			showClose: showClose || false,
			message: message,
			type: type || 'success',
			duration: (duration == 0 ? 5000 : duration)
		});
	}, 100);
}

/**
 *弹出返回消息
 * obj this
 * title 头部
 * message 消息
 * showClose 显示关闭按钮
 * type 确定type success/error/info/warning
 * duration 自动关闭时间
 */
export function openMsgs(obj, title, message, showClose, type, duration) {
	deleteAllNotify(obj);
	if(!validatenull(type) && typeof(type) == 'number') {
		if(type === 2000) {
			type = 'success';
			openMessage(obj, message, showClose, type, duration);
		} else if(type === 2050 || type === -1) {
			type = 'error';
			openMessage(obj, message, showClose, type, duration);
		} else if(type === 2020) {
			openNotify(obj, title, message, true, '');
		}
	} else {
		openMessage(obj, message, showClose, type, duration);
	}
}
/**
 *set字典
 * valueField value对应字段
 * labelField label对应字段
 */
export function setDicts(data, valueField, labelField) {
	for(let d of data) {
		d['dicCode'] = d[valueField]
		d['dicName'] = d[labelField]
		d['value'] = d[valueField]
		d['label'] = d[labelField]
	}
	return data;
}

/**
 *获取字典Label
 * value 值
 * dicts 下来选项
 */
export function getLabel(value, dicts) {
	for(let i in dicts) {
		if(dicts[i].value == value) {
			return dicts[i].label;
		}
		if(dicts[i].dicCode == value) {
			return dicts[i].dicName;
		}
	}
	return '';
}

/**
 *获取字典Label
 * value 值
 * dicts 下来选项
 */
export function getValue(label, dicts) {
	for(let i in dicts) {
		if(dicts[i].label == label) {
			return dicts[i].value;
		}
		if(dicts[i].dicName == label) {
			return dicts[i].dicCode;
		}
	}
	return '';
}

/**
 *多个参数格式化
 * datas参数
 * dateFormats 时间
 * dictFormats 数据字典
 * mappingFields function
 * mergeData 合并
 * cuttingData 切割数据
 */
export function formatTableDatas(datas, dateFormats, dictFormats, mappingFields, mergeData, cuttingData) {
	console.log('formatTableDatas');
	for(const i in datas) {
		datas[i]['number'] = (Number(i) + 1);
		for(let n in dateFormats) {
			datas[i]['format_' + dateFormats[n][0]] = formatDate(datas[i][dateFormats[n][0]], dateFormats[n][1]);
		}
		for(let m in dictFormats) {
			let fun = dictFormats[m].fun + '(\'' + datas[i][dictFormats[m].name] + '\',' + JSON.stringify(dictFormats[m].dicts) + ')';
			let format_value = eval(fun);
			datas[i]['format_' + dictFormats[m].name] = format_value;
		}
		for(let m in mappingFields) {
			let mfs = mappingFields[m].split(':');
			datas[i][mfs[0]] = validatenull(datas[i][mfs[1]]) ? '' : datas[i][mfs[1]] + '';
		}
		for(const m in mergeData) {
			var mergeStr = '';
			var isMerge = false;
			for(const n in mergeData[m]) {
				if(!validatenull(datas[i][mergeData[m][0][n]])) {
					isMerge = true;
				}
				mergeStr += (validatenull(datas[i][mergeData[m][0][n]]) ? '' : datas[i][mergeData[m][0][n]]) + (validatenull(mergeData[m][1][n]) ? '' : mergeData[m][1][n]);
			}
			if(isMerge) {
				datas[i]['format_' + mergeData[m][2]] = mergeStr;
			}
		}
		for(const m in cuttingData) {
			let dataTemp = datas[i][cuttingData[m][0]];
			if(validatenull(dataTemp)) {
				datas[i]['format_' + cuttingData[m][0]] = '';
			} else {
				let d = dataTemp.split(cuttingData[m][1]);
				datas[i]['format_' + cuttingData[m][0]] = d[cuttingData[m][2]];
			}
		}
	}
	return datas.length > 0 ? datas : [];
}

/**
 *格式化时间
 */
export const formatDate = (d, fmt) => {
	var date;
	if(validatenull(d) || (d + '').length == 14) {
		return null;
	} else if(d.length == 28) {
		var dateee = new Date(d).toJSON();
		var date = new Date(new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, ''));
	} else if((d + '').length == 13 || (d + '').length == 21 || (d + '').length == 19) {
		date = new Date(d);
	} else {
		date = d;
	}
	var o = {
		'M+': date.getMonth() + 1, // 月份
		'd+': date.getDate(), // 日
		'h+': date.getHours(), // 小时
		'H+': date.getHours(), // 小时
		'm+': date.getMinutes(), // 分
		's+': date.getSeconds(), // 秒
		'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
		'S': date.getMilliseconds() // 毫秒
	};
	if(/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
	}
	for(var k in o) {
		if(new RegExp('(' + k + ')').test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
		}
	}
	return fmt;
};

/**
 *设置表单字段
 *obj this
 *data 值
 */
export function setTableColumns(obj, datas) {
	console.log('setTableColumns');
	let tableColumns = [];
	for(let i in datas) {
		/*{
    label: '数据类型',
    model: 'dtlDataType',
    width: 120,
  },*/
		let tc = {};
		tc['label'] = datas[i].COLUMN_COMMENT;
		tc['prop'] = datas[i].COLUMN_NAME;
		tc['width'] = datas[i].COLUMN_COMMENT.length * 25;
		tc['dataType'] = datas[i].DATA_TYPE;
		tableColumns.push(tc);
	}
	return tableColumns;
}

/**
 *清除数据
 * data 数据
 * defaultValue 默认值
 */
export function clearData(data, defaultValue) {
	for(let item in data) {
		if(item != 'pageNum' && item != 'pageSize' && item != 'deleteFlag') {
			let isDefault = false;
			for(let i in defaultValue) {
				let key = defaultValue[i].split(':')[0];
				let value = defaultValue[i].split(':')[1];
				if(key == item) {
					data[item] = value;
					isDefault = true;
					break;
				}
			}
			if(!isDefault) {
				data[item] = '';
			}
		}
	}
}

/**
 *设置字段值
 *obj this
 *form赋值
 * formName 表单名称
 */

/*export function setFieldsValue(obj, formName, fieldDatas) {
	setTimeout(() => {
		let fieldsValue = {}
		let formItems = obj.dtlHdrForm.formItems
		for(let item in formItems) {
			fieldsValue[item] = obj[fieldDatas][item]
		}
		obj[formName].setFieldsValue(fieldsValue)
	}, 100)
}*/
/**
 *获取表头
 *obj this
 *form赋值
 * formName 表单名称
 */
export function getHeaders(obj) {
	return {
		Authorization: getToken()
	};
}

/**
 *清空验证
 *obj this
 *name 实体名称
 */
export function clearValidate(obj, name, defaultValue) {
	clearData(obj[name + 'Model'], defaultValue);
	//obj.resetForm(name + 'Ref')
	setTimeout(() => {
		obj.$refs[name + 'Ref'].clearValidate();
	}, 100);
}

/*
 * 删除数组
 * obj this
 * name 实体名称
 * delName 判断删除字段名称
 * delValue 删除字段值
 */
export function delArray(obj, name, delName, delValue) {
	let dataTemp = [];
	if(validatenull(delValue)) {
		openNotify(obj, '删除字段失败', '请选择需要删除的字段', false, 'error');
		return false;
	}
	for(let n in obj[name]) {
		let isDel = false;
		for(let m in delValue) {
			if(delValue[m] == obj[name][n][delName]) {
				isDel = true;
			}
		}
		if(!isDel) {
			dataTemp.push(obj[name][n]);
		}
	}
	obj[name] = dataTemp;
}

/*
 * 插入数组
 * obj this
 * name 实体名称
 * insertName 判断插入字段名称
 * insertNum 插入行
 * insertValue 插入字段值
 */
export function insertArray(obj, name, insertName, insertNum, insertValue) {
	console.log('insertArray');
	let rowKey = 0;
	let defaultValue = JSON.parse(JSON.stringify(insertValue));
	let dataTemp = [];
	for(let n in obj[name]) {
		let isInsert = false;
		if(insertNum == obj[name][n][insertName]) {
			isInsert = true;
		}
		if(isInsert) {
			defaultValue.rowKey = rowKey;
			dataTemp.push(defaultValue);
			rowKey++;
		}
		obj[name][n].rowKey = rowKey;
		dataTemp.push(obj[name][n]);
		rowKey++;
	}
	obj[name] = dataTemp;
}

/*
 * 上移数组
 * obj this
 * name 实体名称
 * moveName 判断移动字段名称
 * moveNum 移动行
 * fun 回调方法
 */
export function moveUpArray(obj, name, moveName, moveNum, fun) {
	let dataTemp = [];
	let rowKey = 0;
	let rowValue = [];
	console.log('moveUpArray');
	for(let n in obj[name]) {
		if((Number(moveNum) - 1) > -1) {
			if((Number(moveNum) - 1) == Number(n)) {
				obj[name][moveNum][moveName] = rowKey;
				dataTemp.push(obj[name][moveNum]);
				rowKey++;
				obj[name][n].rowKey = rowKey;
				dataTemp.push(obj[name][n]);
				rowKey++;
				rowValue.push(dataTemp[Number(moveNum) - 1]);
			} else if(Number(moveNum) != Number(n)) {
				obj[name][n].rowKey = rowKey;
				dataTemp.push(obj[name][n]);
				rowKey++;
			}
		} else {
			obj[name][n].rowKey = rowKey;
			dataTemp.push(obj[name][n]);
			rowKey++;
			if(rowValue.length == 0) {
				rowValue.push(obj[name][moveNum]);
			}
		}
	}
	obj[name] = dataTemp;
	setTimeout(() => {
		obj[fun](rowValue);
	}, 50);
}

/*
 * 下移数组
 * obj this
 * name 实体名称
 * moveName 判断移动字段名称
 * moveNum 移动行
 * fun 回调方法
 */
export function moveDownArray(obj, name, moveName, moveNum, fun) {
	let dataTemp = [];
	let rowKey = 0;
	let rowValue = [];
	console.log('moveDownArray');
	for(let n in obj[name]) {
		if((Number(moveNum) + 1) < obj[name].length) {
			if(Number(moveNum) == Number(n)) {
				obj[name][Number(n) + 1][moveName] = rowKey;
				dataTemp.push(obj[name][Number(n) + 1]);
				rowKey++;
				obj[name][n][moveName] = rowKey;
				dataTemp.push(obj[name][n]);
				rowKey++;
				rowValue.push(dataTemp[Number(moveNum) + 1]);
			} else if((Number(moveNum) + 1) != Number(n)) {
				obj[name][n][moveName] = rowKey;
				dataTemp.push(obj[name][n]);
				rowKey++;
			}
		} else {
			obj[name][n][moveName] = rowKey;
			dataTemp.push(obj[name][n]);
			rowKey++;
			if(rowValue.length == 0) {
				rowValue.push(obj[name][moveNum]);
			}
		}
	}
	obj[name] = dataTemp;
	setTimeout(() => {
		obj[fun](rowValue);
	}, 50);
}

export function exportExecl(title, res) {
	console.log(title);
	var csvData = new Blob([res], {
		type: 'text/csv'
	});
	// for IE
	if(window.navigator && window.navigator.msSaveOrOpenBlob) {
		window.navigator.msSaveOrOpenBlob(csvData, title);
	} else {
		const url = window.URL.createObjectURL(res);
		const a = document.createElement('a');
		a.href = url;
		a.download = title;
		document.body.appendChild(a);
		a.click();
		window.URL.revokeObjectURL(url);
		document.body.removeChild(a);
	}
}

/*
 * list转字符串
 * datas 数据
 */
export function formatArrayToString(datas) {
	let str = '';
	for(const i in datas) {
		str += datas[i] + ',';
	}
	str = str.substring(0, str.length - 1);
	return str;
}

/*
 * listmap转字符串
 * datas 数据
 * name 字段名称
 * division 分隔符
 */
export function formatMapToString(datas, name, division) {
	let str = '';
	for(const i in datas) {
		str += datas[i][name] + division;
	}
	str = str.substring(0, str.length - 1);
	return str;
}

/*
 * listmap转list
 * datas 数据
 * name 字段名称
 */
export function formatMapToArray(datas, name) {
	const list = [];
	for(const i in datas) {
		if(!validatenull(datas[i][name])) {
			list.push(datas[i][name]);
		}
	}
	return list;
}

/**
 *获取list值
 * value 值
 * correspondingField 对应字段
 * returnField 返回字段
 */
export function getListMapValue(datas, value, correspondingField, returnField) {
	for(let i in datas) {
		if(datas[i][correspondingField] == value) {
			return datas[i][returnField];
		}
	}
	return '';
}

/**
 *设置自定义列表选中值
 * obj this
 * name 默认值字段
 * value 选中值
 */
export function setOperationDefault(obj, name, value) {
	obj[name] = '';
	setTimeout(() => {
		obj[name] = value;
	}, 1000);
}

/*
 * 判断是否有选择默认用户主题
 *  obj this
 */
export function hasDefaultProjUser(obj) {
	let projUser = store.state.app.projUser;
	if(validatenull(projUser) || validatenull(projUser.projId)) {
		obj.$alert('请选择用户对应主题', '提示', {
			confirmButtonText: '确定',
			type: 'error',
			callback: action => {}
		});
		return false;
	} else {
		return true;
	}
}

/**
 * 获取导入路径
 */
export function getImportUrl() {
	var url = window.location.href;
	if(url.indexOf('localhost') > -1 || url.indexOf('127.0.0.1') > -1) {
		return 'http://127.0.0.1:9020';
	} else {
		return process.env.VUE_APP_BASEAPI;
	}
}

/**
 * 设置form表单下拉框值
 * modelColumn form表单字段
 * periodFlyag prop字段
 * option 下拉框值
 */
export function setColumnOption(modelColumn, prop, option) {
	for(let column of modelColumn) {
		let props = prop.split(',');
		for(let str of props) {
			if(column.prop == str) {
				column.option = option;
			}
		}
	}
}

/**
 * 获取附件
 * data 值
 */
export function getFiles(data) {
	let fileList = []
	if(!validatenull(data)){
	let files = data.split(",")
	for(let f of files) {
		let name = f.split("/")[f.split("/").length - 1]
		fileList.push({
			"name": name,
			"url": f
		})

	}
	}
	return fileList
}

/**
 * 字符串排序
 * data 值
 */
export function strSort(data) {
	let datas = []
	for(let i = 0 ; i<data.length ; i++){
		datas.push(data.substr(i,1))
	}
	datas = datas.sort(function(a,b){return a - b})
	return  datas.join().replace(",","")
}

/**
 * 下载附件
 * file 值
 */
export function downloadFile(file) {
	window.open(file.url)
}